package com.aizuda.easyManagerTool.service.socket.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aizuda.easy.security.server.EasySecurityServer;
import com.aizuda.easyManagerTool.domain.dto.socket.SocketMessageDTO;
import com.aizuda.easyManagerTool.domain.vo.setting.SettingUserVO;
import com.aizuda.easyManagerTool.service.socket.SocketEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class SocketEventStrategy implements SocketEventService {

    Map<String,SocketEventService> eventServiceMap = new ConcurrentHashMap<>();
    @Resource
    EasySecurityServer easySecurityServer;

    @Autowired
    public SocketEventStrategy(Map<String, SocketEventService> eventServiceMap) {
        this.eventServiceMap = eventServiceMap;
    }

    @Override
    public void onConnect(String token, WebSocketSession session) throws IOException {
        // 解析token
        try {
            SettingUserVO authUser = (SettingUserVO) easySecurityServer.getAuthUser(token);
            SocketSessionManager.add(authUser, session);
            return;
        }catch (Exception e) {
            log.warn("token 进入重新编排 {}", token);
        }
        // 重新编译token
        try {
            // UserID:TenantId:业务:时间戳
            String prefix = token.substring(0, token.indexOf(":"));
            SettingUserVO authUser = (SettingUserVO) easySecurityServer.getAuthUser(prefix);
            token = authUser.getId()+":"+authUser.getTenantId()+token.substring(token.indexOf(":"));
            log.debug("token 重新编排后的 {}",token);
            SocketSessionManager.add(token, session);
        }catch (Exception e){
            log.warn("token 重新编排失败 {}", token);
        }
    }

    @Override
    public void onMessage(String token, WebSocketSession session, SocketMessageDTO socketMessageDTO) throws IOException {
        SocketEventService socketEventService = eventServiceMap.get(socketMessageDTO.getType());
        if(ObjectUtil.isEmpty(socketEventService)){
            return;
        }
        socketEventService.onMessage(token, session, socketMessageDTO);
    }

    @Override
    public void onClose(String token, WebSocketSession session, CloseStatus closeStatus) throws IOException {
        eventServiceMap.values().stream()
                .forEach(i -> {
                    try {
                        i.onClose(token,session,closeStatus);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
        SocketSessionManager.remove(token);
    }

}
